package com.zz.nondatain.base;

import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

/**
 * 所有Activity的基类，处理共有的逻辑
 * @param <T> ViewBinding 类型
 */
public abstract class BaseActivity<T extends ViewBinding> extends AppCompatActivity {
    
    protected T binding;
    private ConnectivityManager connectivityManager;
    private AlertDialog noNetworkDialog;
    private ConnectivityManager.NetworkCallback networkCallback;
    private boolean isNetworkAvailable = true; // 默认认为网络可用
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        // 去掉标题栏
        supportRequestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        
        super.onCreate(savedInstanceState);
        binding = getViewBinding();
        setContentView(binding.getRoot());
        
        // 初始化网络监听
        initNetworkMonitoring();
        
        initView();
        initData();
        initObservers();
    }
    
    /**
     * 初始化网络监听
     */
    private void initNetworkMonitoring() {
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        
        // 初始化时检查网络
        isNetworkAvailable = isNetworkConnected();
        
        // 设置网络回调
        networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                runOnUiThread(() -> {
                    if (!isNetworkAvailable) { // 只有从无网络变为有网络才提示
                        showToast("网络已连接");
                        isNetworkAvailable = true;
                        dismissNoNetworkDialog();
                    }
                });
            }
            
            @Override
            public void onLost(@NonNull Network network) {
                super.onLost(network);
                runOnUiThread(() -> {
                    if (isNetworkAvailable) { // 只有从有网络变为无网络才提示
                        showToast("网络已断开");
                        isNetworkAvailable = false;
                        showNoNetworkDialog();
                    }
                });
            }
            
            @Override
            public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
                super.onCapabilitiesChanged(network, networkCapabilities);
                boolean hasInternet = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
                boolean hasValidated = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
                
                if (hasInternet && hasValidated) {
                    runOnUiThread(() -> {
                        boolean isWifi = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
                        boolean isCellular = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
                        
                        if (isWifi) {
                            showToast("当前网络: WiFi");
                        } else if (isCellular) {
                            showToast("当前网络: 移动数据");
                        }
                    });
                }
            }
        };
        
        // 注册网络回调
        NetworkRequest networkRequest = new NetworkRequest.Builder()
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .build();
        connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
        
        // 如果当前没有网络，显示无网络弹窗
        if (!isNetworkAvailable) {
            showNoNetworkDialog();
        }
    }
    
    /**
     * 检查网络是否连接
     */
    private boolean isNetworkConnected() {
        if (connectivityManager == null) return false;
        
        Network network = connectivityManager.getActiveNetwork();
        if (network == null) return false;
        
        NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
        return capabilities != null && 
               capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
               capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
    }
    
    /**
     * 显示无网络弹窗
     */
    private void showNoNetworkDialog() {
        if (isFinishing() || noNetworkDialog != null && noNetworkDialog.isShowing()) return;
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("网络未连接")
                .setMessage("请检查您的网络设置")
                .setCancelable(false)
                .setPositiveButton("设置", (dialog, which) -> {
                    // 可以跳转到网络设置页面
                    startActivity(new android.content.Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                })
                .setNegativeButton("取消", null);
        
        noNetworkDialog = builder.create();
        noNetworkDialog.show();
    }
    
    /**
     * 关闭无网络弹窗
     */
    private void dismissNoNetworkDialog() {
        if (noNetworkDialog != null && noNetworkDialog.isShowing()) {
            noNetworkDialog.dismiss();
            noNetworkDialog = null;
        }
    }
    
    @Override
    protected void onDestroy() {
        // 注销网络回调
        if (connectivityManager != null && networkCallback != null) {
            connectivityManager.unregisterNetworkCallback(networkCallback);
        }
        
        dismissNoNetworkDialog();
        super.onDestroy();
    }
    
    /**
     * 初始化视图
     */
    protected abstract void initView();
    
    /**
     * 初始化数据
     */
    protected abstract void initData();
    
    /**
     * 初始化观察者
     */
    protected abstract void initObservers();
    
    /**
     * 获取ViewBinding实例
     */
    protected abstract T getViewBinding();
    
    /**
     * 显示Toast消息
     */
    protected void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
} 